package com.myproject.mall.seller.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.myproject.mall.common.constants.RedisConstants;
import com.myproject.mall.domain.entity.Brand;
import com.myproject.mall.domain.enums.BrandStatus;
import com.myproject.mall.seller.mapper.BrandMapper;
import com.myproject.mall.seller.service.IBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BrandServiceImpl implements IBrandService {
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Transactional
    @Override
    public void addBrand(Brand brand) {
        int insert = brandMapper.insert(brand);
        if(insert == 1) {
            stringRedisTemplate.opsForHash().put(RedisConstants.BRAND_KEY, brand.getId().toString(), brand.getBrandName());
        }
    }

    @Override
    public Brand getBrand(Long id) {
        return brandMapper.selectById(id);
    }

    @Override
    public void updateBrand(Brand brand) {
        brandMapper.updateById(brand);
    }

    @Override
    public void deleteBrand(Long id) {
        int update = brandMapper.update(new LambdaUpdateWrapper<Brand>()
                .eq(Brand::getId, id)
                .set(Brand::getStatus, BrandStatus.DELETED));
        if (update == 1) stringRedisTemplate.opsForHash().delete(RedisConstants.BRAND_KEY, id.toString());
    }

    @Override
    public List<Brand> getAllBrand() {
        return brandMapper.selectList(new LambdaQueryWrapper<Brand>().eq(Brand::getStatus, BrandStatus.NORMAL));
    }
}
